<template>
  <div class="create-or-edit">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '编辑广告位' : '添加广告位' }}</span>
      </div>
      <el-form ref="form" :model="content" label-width="80px">
        <el-form-item label="广告名称">
          <el-input v-model="content.name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getSpaceById, saveOrUpdate } from '@/services/advert-space'

export default {
  name: 'CreateOrEdit',
  // 通过 props 接收父组件传值，判断当前是哪种功能(添加或编辑)
  props: {
    isEdit: {
      type: Boolean,
      // 默认添加功能
      defauly: false
    }
  },
  data () {
    return {
      content: {
        // 广告位名称
        name: ''
      }
    }
  },
  created () {
    if (this.isEdit) {
      this.loadgetSpaceById()
    }
  },
  methods: {
    // 保存或者新增资源
    async onSubmit () {
      const { data } = await saveOrUpdate(this.content)
      if (data.state === 1) {
        // 关闭提示框（需要子组件向父组件传递状态）
        this.$emit('success')
        this.$message.success(`${this.isEdit === true ? '修改' : '添加'}成功`)
        this.$router.push({
          name: 'advert-space'
        })
      }
    },
    // 根据ID获取广告位
    async loadgetSpaceById () {
      const id = this.$route.params.id
      const { data } = await getSpaceById(id)
      if (data.state === 1) {
        this.content = data.content
      }
    },
    // 重置按钮清空数据
    onReset () {
      this.content[this.$route.params.id] = {}
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
